import AuthUserApi from '@/api/auth/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),  // 设置token初始状态
  roles: [],       // 用户角色
  userCode: '',   // 用户编码
  userName: '',   // 用户名
  orgCode: '',
  orgName: ''
}

const mutations = {
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 设置角色
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER_NAME: (state, userName) => {
    state.userName = userName
  },
  SET_USER_CODE: (state, userCode) => {
    state.userCode = userCode
  },
  SET_ORG_NAME: (state, orgName) => {
    state.orgName = orgName
  },
  SET_ORG_CODE: (state, orgCode) => {
    state.orgCode = orgCode
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {    //userinfo是表单传过来的对象
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 调用@/api/auth/user.js中checkToken()登录方法
      AuthUserApi.login(userInfo).then(response => {
        // 解构后端返回的数据
        const { data } = response
        // 将返回的token信息保存到store
        commit('SET_TOKEN', data.token)
        // 设置token:将token设置到cookie中
        setToken(data.token)
      }).catch(error => {
        // 拒绝访问
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      AuthUserApi.getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { permissions } = data

        // roles must be a non-empty array
        if (!permissions || permissions.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        // 将用户信息保存到vuex中
        commit('SET_ROLES', permissions)         // 设置角色
        commit('SET_USER_NAME', data.userName)  // 设置用户名称
        commit('SET_USER_CODE', data.userCode)  // 设置用户编码
        commit('SET_ORG_NAME', data.orgName)
        commit('SET_ORG_CODE', data.orgCode)
        resolve({
          roles: permissions,
          userCode: data.userCode,
          userName: data.userName,
          orgCode: data.orgCode,
          orgName: data.orgName
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 调用api
      AuthUserApi.logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')   // 删除vuex的token
      commit('SET_ROLES', [])
      removeToken()              // 先删除vuex的token，再清除缓存
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
